<template>
	<view class="zuipageWrap">
		<view class="J_conditionWrap uni-flex">
			<view class="J_condition J_suplier" :style="{width: conditionWidth}">
				<picker class="zpicker" @change="bindPickerChange" :value="supplierIndex" :range="supplierList" range-key="name">
					<view class="uni-input uni-ellipsis zinput">{{supplierList[supplierIndex].name}}</view>
				</picker>
			</view>
			<view class="J_condition J_split"></view>
			<view class="J_condition J_drugStorage" :style="{width: conditionWidth}">
				<picker class="zpicker" @change="bindPickerChangeD" :value="drugStorageIndex" :range="drugStorageList" range-key="name">
					<view class="uni-input uni-ellipsis zinput">{{drugStorageList[drugStorageIndex].name}}</view>
				</picker>
			</view>
		</view>
		<view class="J_top">
			<uniIcon type="search" size="26" class="J_searchIcon"></uniIcon>
			<view class="J_search">
				<input class="uni-input" confirm-type="search" placeholder="请输入药品信息"
					v-model="invoiceId" @input="inputEvent" @confirm="inputConfirm" :maxlength="maxlength" :focus="triggerFocus1" />
			</view>
			<uniIcon type="camera" size="26" class="J_scanIcon" @click="actionSheetTap"></uniIcon>
		</view>
		
		<view class="J_content">
			<view class="J_card" v-for="(item, index) in tableData" :key="index" :class="{isSlide: !item.slideHide}">
				<view class="uni-flex uni-row" @click="zslide(item, index)">
					<view class="J_tit">
						<view class="J_cicon"></view>
						{{item.name}}
						<uniIcon type="arrowdown" size="20" class="J_slideIcon" v-if="item.slideHide"></uniIcon>
						<uniIcon type="arrowup" size="20" class="J_slideIcon" v-if="!item.slideHide"></uniIcon>
					</view>
				</view>
				<view class="uni-flex uni-row">
					<view class="J_label">订单数：</view>
					<view class="J_des">{{item.num}}</view>
				</view>
				<view class="uni-flex uni-row J_editWrap" @click="changeNum(item, index)">
					<view class="J_label">扫码数：</view>
					<view class="J_des">
						{{item.smnum}}
						<uniIcon type="compose" size="26" class="J_editIcon"></uniIcon>
					</view>
				</view>
				<view class="uni-flex uni-row" :class="{no_border: item.slideHide}">
					<view class="J_label">规格：</view>
					<view class="J_des">{{item.specifications}}</view>
				</view>
				<view class="uni-flex uni-row" :class="{isSlide: item.slideHide}">
					<view class="J_label">单位：</view>
					<view class="J_des">{{item.unit}}</view>
				</view>
				<view class="uni-flex uni-row" :class="{isSlide: item.slideHide}">
					<view class="J_label">厂商：</view>
					<view class="J_des">{{item.factory}}</view>
				</view>
				<view class="uni-flex uni-row" :class="{isSlide: item.slideHide}">
					<view class="J_label">药库：</view>
					<view class="J_des">{{item.drugstorage}}</view>
				</view>
				<view class="uni-flex uni-row" :class="{isSlide: item.slideHide}">
					<view class="J_label">货位：</view>
					<view class="J_des">{{item.locatno}}</view>
				</view>
				<view class="uni-flex uni-row" :class="{isSlide: item.slideHide}">
					<view class="J_label">架位：</view>
					<view class="J_des">{{item.jwcode}}</view>
				</view>
				<view class="uni-flex uni-row" :class="{isSlide: item.slideHide}">
					<view class="J_label">单价：</view>
					<view class="J_des">{{item.unitprice | priceFormat(2,'￥',true)}}</view>
				</view>
				<view class="uni-flex uni-row" :class="{isSlide: item.slideHide}">
					<view class="J_label">金额：</view>
					<view class="J_des">{{item.price | priceFormat(2,'￥',true)}}</view>
				</view>
				<view class="uni-flex uni-row" :class="{isSlide: item.slideHide}">
					<view class="J_label">批号：</view>
					<view class="J_des">{{item.batchnumber}}</view>
				</view>
				<view class="uni-flex uni-row" :class="{isSlide: item.slideHide}">
					<view class="J_label">有效期：</view>
					<view class="J_des">{{item.validity}}</view>
				</view>
				<view class="uni-flex uni-row" :class="{isSlide: item.slideHide}">
					<view class="J_label">生产日期：</view>
					<view class="J_des">{{item.productdate}}</view>
				</view>
				<view class="uni-flex uni-row" :class="{isSlide: item.slideHide}">
					<view class="J_label">发票号：</view>
					<view class="J_des">{{item.invoicecode}}</view>
				</view>
			</view>
		</view>
		<view class="uni-btn-v J_foot" v-if="showBtnFlag">
			<button type="default" class="zbtn J_last" @click="lastRes">上一次</button>
			<button type="default" class="zbtn J_cancel" @click="cancle">取消</button>
			<button class="zbtn J_sub" @click="save">提交</button>
		</view>
		
		<uni-popup :show="zpopupFlag" position="middle" mode="middle" @hidePopup="hidezpop">
			<view class="zpopupWrap uni-tip">
				<view class="uni-tip-title">医内物流</view>
				<view class="uni-tip-subtit">请输入扫码数量</view>
				<view class="uni-tip-content">
					<view class="J_inputWrap">
						<input class="uni-input" type="number" v-model="invoiceId_temp" :maxlength="maxlength" :focus="triggerFocus_temp" />
					</view>
				</view>
				<view class="uni-tip-group-button">
					<view class="uni-tip-button" @click="hidezpop">取消</view>
					<view class="uni-tip-button" @click="surezpop">确定</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import uniIcon from "@/components/uni-icon/uni-icon.vue";
import uniPopup from "@/components/uni-popup/uni-popup.vue";
import {zMedcheckByCode, zMedcheckSave, zSupplierList, zDrugStorageList} from '@/util/api';
import {
	mapState,mapGetters,mapMutations,mapActions
} from 'vuex'
export default {
	components: {uniIcon, uniPopup},
	data() {
		return {
			tableData: [],
			lastResBack: {
				invoiceId: '',
				supplierIndex: '',
				drugStorageIndex: ''
			},
			invoiceId: '',
			maxlength: 20,
			triggerFocus1: false,
			supplierIndex: 0,
			supplierList: [
				{
					id: '',
					name: '供应商'
				}
			],
			drugStorageIndex: 0,
			drugStorageList: [
				{
					id: '',
					name: '药库'
				}
			],
			conditionWidth: '',
			showBtnFlag: false,
			curItem_temp: null,
			triggerFocus_temp: false,
			zpopupFlag: false,
			invoiceId_temp: ''
		}
	},
	computed: {
		...mapState(['pid'])
	},
	onLoad(e) {
		let _that = this;
		uni.getSystemInfo({
			success: function (res) {
				_that.conditionWidth = ((res.windowWidth - 2)/2).toFixed(1)+'px';
			}
		});
		
		let medCheckRes = uni.getStorageSync('medCheckRes');
		if(medCheckRes){
			medCheckRes = JSON.parse(medCheckRes);
			this.lastResBack = medCheckRes;
		}
		
		uni.$on('zCategoryCode',function(data){
			if(data)
				_that.fetchInvoice();
		})
		
		this.fetchAllData();
	},
	onNavigationBarButtonTap(e) {
		uni.navigateTo({
			url: '/pages/medcheck/list?sid='+this.supplierIndex
		});
	},
	onUnload() {
		uni.$off('zCategoryCode');
		this.setLastRes();
	},
	methods: {
		async fetchAllData () {
			let res = await zSupplierList();
			res = this.zutil.formatAxiosData(res);
			let res2 = await zDrugStorageList();
			res2 = this.zutil.formatAxiosData(res2);
			if(res.status == 0){
				this.supplierList = res.data;
			}else{
				this.zutil.ztip(res.description || "获取供应商列表失败！");
			}
			if(res2.status == 0){
				this.drugStorageList = res2.data;
			}else{
				this.zutil.ztip(res2.message || "获取药库列表失败！");
			}
		},
		async fetchInvoice () {
			this.triggerFocus1 = false;
			this.showBtnFlag = false;
			uni.hideKeyboard();
			this.setLastRes();
			let tpl_param = {
        yjmNo: this.invoiceId,
				supplierid: this.supplierList[this.supplierIndex].id,
				drugStorageid: this.drugStorageList[this.drugStorageIndex].id
      }
			this.tableData = [];
			uni.showLoading({title: '加载中', mask: true});
			let res = await zMedcheckByCode(tpl_param);
      res = this.zutil.formatAxiosData(res);
			//console.log(JSON.stringify(res));			
			
			uni.hideLoading();
			//this.tableData = res.data;
			if(res.status == 0){						
				this.tableData = res.data.list;
				this.showBtnFlag=true;
				// this.invoiceId = '';
				// this.triggerFocus1=true;
			}else if(res.status == 1){
				this.zutil.ztip("药监码重复");
					this.zutil.zuiShaker();
				this.tableData = res.data.list;
				this.invoiceId = '';
				this.showBtnFlag=true;
			}else if(res.status == 2){
				this.zutil.zconfirm("类别码未对照，是否进入对照页面？", (type)=>{
					if(type){
						// 确定
						let attr = {
							id: this.invoiceId,
							type: 1
						}
						uni.setStorageSync('medCheckInfo', JSON.stringify(attr));
						uni.navigateTo({
							url: '/pages/categorycode/index'
						});
					}else{
						// 取消
					}
				});
			}else{
				this.zutil.ztip(res.description);
				this.zutil.zuiShaker();
			}
			
			this.lastResBack.invoiceId = this.invoiceId;
			this.lastResBack.supplierIndex = this.supplierIndex;
			this.lastResBack.drugStorageIndex = this.drugStorageIndex;
		},
		inputEvent (e) {
			/* let _val = e.detail.value;
			if(_val.length == this.maxlength)
				this.fetchInvoice(); */
		},
		inputConfirm (e) {
			let _val = e.detail.value;
			//if(_val.length == this.maxlength)
				this.fetchInvoice();
		},
		cancle () {
			this.setLastRes();
			this.invoiceId = '';
			this.tableData = [];
			this.triggerFocus1 = false;
			setTimeout(()=>{
				this.triggerFocus1 = true;
			}, 50)
		},
		save () {
			if(!this.tableData.length){
				this.zutil.ztip("请输入药品信息或者扫码药品条码");
				return false;
			}
			this.zutil.zconfirm("是否确认复核该药品？", (type)=>{
				if(type){
					// 确定
					this.saveS();
				}else{
					// 取消
				}
			});
		},
		async saveS () {
			let tpl_param = {
				invoiceId: this.invoiceId,
				datas: []
			}
			this.tableData.forEach(v=>{
				let attr = {
					id: v.id,
					smnum: v.smnum,
					whid: v.whid,
					jwid: v.jwid,
					locatid: v.locatid,
				}
				tpl_param.datas.push(attr);
			})
			uni.showLoading({title: '加载中', mask: true});
			let res = await zMedcheckSave(tpl_param);
			res = this.zutil.formatAxiosData(res);
			uni.hideLoading();
			if(res.status == '0'){
				this.zutil.ztip(res.description || "复核药品成功");
				this.cancle();
			}else{
				this.zutil.zalert(res.description || "复核药品失败！");
				this.zutil.zuiShaker();
			}
		},
		zslide (item, index) {
			let slideFlag = item.slideHide;
			this.$set(item, 'slideHide', !slideFlag);
		},
		scanCode () {
			var _that = this;
			uni.scanCode({
				success: function (res) {
					_that.cancle();
					let cres = res.result;
					_that.invoiceId = cres;
					_that.fetchInvoice();
				},
				fail: function (res) {}
			})
		},
		//将图片压缩转成base64
		getBase64Image(img) {
			var canvas = document.createElement("canvas");
			var width = img.width;
			var height = img.height;
			// calculate the width and height, constraining the proportions
			if (width > height) {
				if (width > 1000) {
					height = Math.round(height *= 1000 / width);
					width = 1000;
				}
			} else {
				if (height > 1000) {
					width = Math.round(width *= 1000 / height);
					height = 1000;
				}
			}
			canvas.width = width;   /*设置新的图片的宽度*/
			canvas.height = height; /*设置新的图片的长度*/
			var ctx = canvas.getContext("2d");
			ctx.drawImage(img, 0, 0, width, height); /*绘图*/
			var dataURL = canvas.toDataURL("image/jpeg", 0.5);
			// return dataURL.replace("data:image/png;base64,", "");
			return dataURL;
		},
		scanCodeS () {
			let _that = this;
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				success: function (res) {
					console.log(res);
					// let newFile = null;
					// var image = new Image();
					// image.src = res.tempFilePaths[0];
					// image.onload = function() {
					// 	newFile = _that.getBase64Image(image);
					// 	console.log(newFile);
						uni.showLoading({title: '加载中', mask: true});
						uni.uploadFile({
							url: 'http://218.65.83.72:8099/rest/uploadpic', //仅为示例，非真实的接口地址
							// url: 'https://unidemo.dcloud.net.cn/upload',
							fileType: 'image',
						  filePath: res.tempFilePaths[0],
						  name: 'file',
						  formData: {
								'user': 'test'
						  },
						  success: (uploadFileRes) => {
								let res = uploadFileRes.data;
								if(res)
									res = JSON.parse(res);
								console.log(res);
								if(res.status == 0){
									_that.invoiceId = res.data;
									_that.fetchInvoice();
								}else{
									_that.zutil.zalert(res.description || "图片上传失败！");
								}
						  },
							fail: (e) => {
								console.log(e);
							},
							complete () {
								uni.hideLoading();
							}
						});
					// }
				}
			});
		},
		bindPickerChange: function(e) {
			this.supplierIndex = e.target.value;
		},
		bindPickerChangeD: function(e) {
			this.drugStorageIndex = e.target.value;
		},
		changeNum (item, index) {
			this.curItem_temp = item;
			this.zpopupFlag = true;
			this.triggerFocus_temp = true;
			return false;
			// #ifdef APP-PLUS
			let _that = this;
			plus.nativeUI.prompt("请输入扫码数量: ", function(e){
				if(e.index==0){
					let _val = parseInt(e.value, 10);
					if(_val){
						item.smnum = _val;
					}
				}
			}, "医内物流", item.smnum, ["确定","取消"]);
			// #endif
		},
		lastRes () {
			let medCheckRes = uni.getStorageSync('medCheckRes');
			if(medCheckRes){
				medCheckRes = JSON.parse(medCheckRes);
				this.lastResBack = medCheckRes;
				this.invoiceId = medCheckRes.invoiceId;
				this.supplierIndex = medCheckRes.supplierIndex;
				this.drugStorageIndex = medCheckRes.drugStorageIndex;
			}
			this.fetchInvoice();
		},
		setLastRes () {
			uni.setStorageSync('medCheckRes', JSON.stringify(this.lastResBack));
		},
		hidezpop () {
			this.invoiceId_temp = '';
			this.zpopupFlag = false;
			this.triggerFocus_temp = false;
		},
		surezpop () {
			let val = parseFloat(this.invoiceId_temp) || 0;
			this.curItem_temp.smnum = val?val.toFixed(4):0;
			this.hidezpop();
		},
		actionSheetTap () {
			uni.showActionSheet({
				title:'医内物流',
				itemList: ['拍照', '扫码'],
				success: (e) => {
					if(e.tapIndex == 0){
						this.scanCodeS();
					}else if(e.tapIndex == 1){
						this.scanCode();
					}
				}
			})
		}
	},
	filters:{
		//价格过滤器
		// arg表示原始参数,num表示小数点位,默认保留两位,symbol表示符号,spilt是否进行逗号分隔【true，false】
		priceFormat:function (arg,num=0,symbol,spilt=false) {
			/**
			 * 默认数字: {{number|priceFormat()}}
				保留两位小数: {{number|priceFormat(2)}}
				保留三位小数: {{number|priceFormat(3)}}
				添加￥符号并保留两位: {{number|priceFormat(2,'￥')}}
				添加$符号并保留三位: {{number|priceFormat(3,'$')}}
				添加千分号符号: {{number|priceFormat(0,'',true)}}
				添加千分号符号并保留两位: {{number|priceFormat(2,'',true)}}
				添加￥和千分号符号并保留两位: {{number|priceFormat(2,'￥',true)}}
			 **/
			arg=Number(arg).toFixed(num);
			if(spilt==true){
				if (arg.indexOf('.') == -1) {
					arg=arg.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
				}else{
					var parts = arg.split(".");
					parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
					arg=parts.join(".");
				}
			}
			if(symbol){
				arg=symbol+arg;
			}
			return arg;
		},
	}
}
</script>

<style scoped lang="scss">
.zuipageWrap {
	background: #F5F5F5;
	height: 100%;
	
	.J_top {
		position: relative;
		padding: 20upx;
		background: #fff;
		
		.J_searchIcon {
			position: absolute;
	    left: 46upx;
	    top: 34upx;
	    z-index: 99;
		}
		.J_search {
			width: 100%;
			height: 80upx;
			display: flex;  
	    align-items: center;
			
			.uni-input {
				height: 80upx;
				line-height: 80upx;
				min-height: 80upx;
				padding: 0 100rpx 0 88upx;
				border: 2upx solid #ddd;
				border-radius: 40upx;
			}
		}
		.J_scanIcon {
			position: absolute;
			right: 36upx;
			top: 34upx;
			z-index: 99;
			width: 80upx;
			text-align: center;
		}
	}
	
	.J_content {
		padding: 20upx 0 60px;
		background: #F5F5F5;
		.J_card {
			border-top: 2upx solid #ddd;
			border-bottom: 2upx solid #ddd;
			height: auto;
			background: #fff;
			padding: 0 32upx;
			color: #3C3C3C;
			margin-bottom: 20upx;
			overflow: hidden;
			
			&.isSlide, &:first-child {
				height: auto;
			}
			
			&:last-child {
				margin-bottom: 0;
			}
	
			.uni-row {
				border-bottom: 2upx solid #e5e5e5;
				padding: 18upx 0;
				&.no_border {
					border-bottom: 0;
				}
				&:first-child {
					padding: 28upx 0;
				}
				&:last-child {
					border-bottom: 0;
				}
				&.isSlide {
					display: none!important;
				}
				.J_tit {
					height: 44upx;
					line-height: 44upx;
					font-size: 30upx;
					position: relative;
					padding-left: 32upx;
					font-weight: bold;
					overflow: hidden;
					width: 100%;
					.J_cicon {
						position: absolute;
						left: 0;
						top: 0;
						width:12upx;
						height: 44upx;
						background: #FFC12E;
						display: block;
					}
					.J_slideIcon {
						position: absolute;
						right: 0;
						top: 6upx;
					}
				}
				.J_label {
					width: 184upx;
				}
				.J_des {
					flex: 1;
					position: relative;
					text-align: right;
					.uni-input {
						padding: 0 56upx 0 24upx;
					}
				}
				
				&.J_editWrap {
					position: relative;
					padding-right: 52upx;
					border-bottom: 2upx solid #ffb200;
					.J_editIcon {
						position: absolute;
						right: -52upx;
						top: 0;
						width: 40upx;
					}
				}
			}
		}
	}
	
	.uni-btn-v {
		display: flex;
		justify-content: center;
		&.J_foot {
			position: fixed;
	    bottom: 0;
	    left: 0;
	    right: 0;
			background: #fff;
	    box-shadow: 0px 0px 20upx rgba(0,0,0,0.2);
			padding: 0;
		}
		.zbtn {
			width: 24%;
			font-size: 32upx;
	    display: block;
	    border-radius: 0;
	    margin: 0;
	    height: 100upx;
	    line-height: 100upx;
			background: #fff;
			&:after {
				width: 0;
				height: 0;
			}
		}
		.J_last {
			background: #eabc4f;
			color: #fff;
		}
		.J_cancel {
			color: #000;
		}
		.J_sub {
			background: #018DEE;
	    color: #fff;
			flex: 1;
		}
	}
}

.J_conditionWrap {
		align-items: center;
	.J_condition {
    position: relative;
    height: 100upx;
    margin-bottom: 20upx;
		width: calc((100% - 2px)/2);
		&.J_split {
			width: 4upx;
			height: 100upx;
			background: transparent;
			&:after {
				content: '';
				width: 4upx;
				height: 80upx;
				background: #FFC12E;
				display: block;
				position: absolute;
				top: 10upx;
				left: 0;
			}
		}
		.zpicker {
			.zinput {
				display: inline-block;
				width: 100%;
				border: 2upx solid #fff;
				background: #fff;
				height: 100upx;
				line-height: 100upx;
				text-align: center;
				padding: 0;
				overflow: hidden;
				div {
					width: 100%;
					text-align: center;
					input {
						width: 90%;
						text-align: center;
					}
				}
			}
		}
		.J_slideIcon {
			position: absolute;
			top: 34upx;
			right: 0;
		}
	}
}
</style>
